package models

import (
	"fmt"
	"time"
	"github.com/astaxie/beego/orm"
)
type YyStatChapterUv struct {
	Id 			int64 	`pk:"auto"`
	BookId 		int64	`json:"book_id"`
	ChapterId	int64	`json:"chanpter_id"`
	Uv 			int64	`json:"uv"`
	Platform 	int		`json:"platfrom"`
	CreatedAt 	string	`json:"created_at"`
	UpdatedAt 	string	`json:"updated_at"`
}

type Book struct {
	ChapterId int64
	VisitNum int64
	BookId int64
}

func init() {
	// 需要在init中注册定义的model
	orm.RegisterModel(new(YyStatChapterUv))
}

/**
章节保存率
@platfrom 1:十音；2:cps
@
 */
func AnalysisChapterData(platform int, chapterData []*Book) {
	o := orm.NewOrm()
	nowTime := time.Now().Format("2006-01-02 15:04:05")
	for _, v :=range chapterData {
		var stat YyStatChapterUv //循环每次必须赋新的内存地址
		chapter_id := v.ChapterId
		visit_num := v.VisitNum
		book_id := v.BookId

		num, _:= o.QueryTable(stat).Filter("chapter_id", chapter_id).Filter("book_id", book_id).Count()
		if num == 0 {
			stat.BookId          = book_id
			stat.ChapterId       = chapter_id
			stat.Uv              = visit_num
			stat.Platform        = platform
			stat.CreatedAt       = nowTime
			stat.UpdatedAt       = nowTime
			_, err := o.Insert(&stat)
			if err != nil {
				fmt.Println(err)
			}
		} else {
			_, err := o.QueryTable(stat).Filter("chapter_id", chapter_id).Filter("book_id", book_id).Update(orm.Params{
				"uv": orm.ColValue(orm.ColAdd, visit_num),
				"updated_at": nowTime,
			})
			if err != nil {
				fmt.Println(err)
			}
		}
	}
}

